package com.fandy.struts.action;

import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import com.fandy.struts.DAL.DALStaff;
import com.fandy.struts.form.FormLogin;
import com.fandy.struts.form.FormReg;
import com.fandy.struts.util.MappingForward;

public class ActionReg extends DispatchAction {

	/* (non-Javadoc)
	 * @see org.apache.struts.actions.DispatchAction#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		
		ActionForward af =null;
		FormReg  fr= (FormReg)form;
		DALStaff ds = new DALStaff();
		ActionErrors ae = new ActionErrors();
		
		ResultSet rs = ds.existStaff(fr.getName());
		
		rs.next();
		
		if(rs.getInt(1)>=1)
		{
			ae.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("Error.Register.UserName"));
			
			System.out.println(fr.getName()+"   already exist !");
			
			saveErrors(request, ae);
			
			af = mapping.findForward(MappingForward.Failure);
			
			return af;
		}		
		
		
		 if(ds.Add(fr.getStf())==1)
		{
			 System.out.println(fr.getName()+"   Registered !");
		}
		
		 request.getSession().setAttribute("UserInfo", new FormLogin().setStaff(fr.getStf()));
		 
		af = mapping.findForward(MappingForward.Success);
		
		return af;	
		
	}

	
}
